package com.fengye.security.utils;

import com.fengye.security.custom.model.LoginUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;

/**
 * SecurityUtils
 *
 * @author 枫叶fy
 * @description spring security工具类
 * @since 2024/2/29 21:52
 */
public class SecurityUtils {

    /**
     * 获取当前登录状态的Authentication
     * @return Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户信息
     * @return 用户信息
     */
    public static LoginUserDetails getLoginUser() {
        if (Objects.nonNull(getAuthentication())) {
            return (LoginUserDetails) getAuthentication().getPrincipal();
        }
        return null;
    }

    /**
     * 获取Userid
     * @return userid
     */
    public static Long getUserId () {
        if (Objects.nonNull(getLoginUser())) {
            return getLoginUser().getUser().getId();
        }
        return null;
    }

    /**
     * 判断是否是admin管理员
     * @return 是否admin
     */
    public static Boolean isAdmin() {
        if (Objects.nonNull(getLoginUser())) {
            String type = getLoginUser().getUser().getType();
            return "1".equals(type);
        }
        return false;
    }
}
